<?php

namespace app\common\model\xilumarket;

use app\common\model\User;
use think\Db;
use think\Exception;
use think\Model;
use traits\model\SoftDelete;
use function fast\array_except;
use function fast\array_get;


class TopicForumComment extends Model
{
    use SoftDelete;
    // 表名
    protected $name = 'xilumarket_topic_forum_comment';

    protected $autoWriteTimestamp = 'int';

    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    protected $append = [
        'createtime_text'
    ];

    public static function init() {
        $updateTopicForumComment = function($row) {
            $forum_id = $row->forum_id;
            $count = Db::name('xilumarket_topic_forum_comment')
                ->where('forum_id',$forum_id)
                ->whereNUll('deletetime')
                ->count();
            Db::name('xilumarket_topic_forum')->where('id',$forum_id)->update(['comment_count'=>$count]);
        };
        self::afterInsert($updateTopicForumComment);
        self::afterDelete($updateTopicForumComment);
    }
    public function getCreatetimeTextAttr($value,$data){
        if(isset($data['createtime'])){
            return xilumarket_time_cha(time(),$data['createtime']);
        }
        return '';
    }

    public function user() {
        return $this->belongsTo(User::class, 'user_id')->setEagerlyType(0);
    }

    public static function addComment($params) {
        $forum_id = array_get($params,'forum_id');
        if(!$forum_id){
            throw new Exception("参数错误");
        }
        $forum = TopicForum::get($forum_id);
        if(!$forum || $forum->status == 'hidden'){
            throw new Exception("不允许评论");
        }

        $pid = array_get($params,'pid');
        if($pid){
            $pcomment = self::where('id',$pid)->field('user_id,top_id')->find()?:[];
            $params['puser_id'] = $pcomment ? $pcomment['user_id'] : 0;
            $params['top_id'] = empty($pcomment['top_id']) ? $pid : $pcomment['top_id'];
        }
        try {

            $images = array_get($params,'images');
            $params['images'] = $images? (is_array($images) ? implode(',',$images) : $images) :'';
            $params['content'] = array_get($params,'content', '');
            check_sens_word($params['content']);
            $params['status'] = 'normal';
            if($id = array_get($params,'id')){
                $comment = self::get($id);
                $ret = $comment?$comment->save(array_except($params,'id')):false;
            }else{
                $comment = new self();
                $ret = $comment->allowField(true)->save($params);
            }
            if ($ret === false) {
                throw new Exception($comment->getError());
            }
            return $comment;
        }catch (\Exception $e) {
            throw $e;
        }
    }
}
